<template>
  <BasicModal
    @register="registerModal"
    v-bind="$attrs"
    title="修改资产配置文件"
    @ok="handleSubmit"
    :destroyOnClose="true"
    :closeFunc="close"
    :body-style="{ marginLeft: '10px', marginRight: '10px' }"
  >
    <AssetFilesDetailForm
      :formData="deviceFileData"
      ref="assetFileDetailForm"
      @upload="getImgData"
      @delete-img="deleteImgData"
    />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import AssetFilesDetailForm from './AssetFilesDetailForm.vue';
  import { ref } from 'vue';
  import {
    postAssetProfile,
    getAssetProfileById,
  } from '/@/api/thingsborad/profile/assetProfile/assetProfile';
  import dayjs from 'dayjs';
  const emit = defineEmits(['edit']);
  //资产配置详情
  const deviceFileData = ref<Recordable>({});
  // assetFileDetailForm资产配置详情表单实例
  const assetFileDetailForm = ref<any>(null);
  //图片
  let imgData = ref<any>(null);
  const [registerModal, { closeModal }] = useModalInner(async (data) => {
    try {
      let param = '/' + data.record.id;
      getAssetProfileById(param).then((res) => {
        deviceFileData.value = res;
      });
    } catch (error) {
      console.error('获取配置信息失败', error);
    }
  });
  function getImgData(data: any) {
    imgData.value = data;
  }
  function deleteImgData() {
    imgData.value = null;
  }

  async function close() {
    imgData.value = null;
    return true;
  }
  async function handleSubmit() {
    await assetFileDetailForm.value.validate().then(async (res) => {
      if (res.defaultDashboardId != undefined) {
        res.defaultDashboardId = JSON.parse(res.defaultDashboardId);
      }
      if (res.defaultEdgeRuleChainId != undefined) {
        res.defaultEdgeRuleChainId = JSON.parse(res.defaultEdgeRuleChainId);
      }
      if (res.defaultRuleChainId != undefined) {
        res.defaultRuleChainId = JSON.parse(res.defaultRuleChainId);
      }
      res.image = imgData.value;
      Object.assign(deviceFileData.value, res);
      let dateObject = dayjs(deviceFileData.value.createdTime, 'YYYY-MM-DD HH:mm:ss');
      deviceFileData.value.createdTime = dateObject.valueOf();

      await postAssetProfile(deviceFileData.value);
    });
    emit('edit');
    imgData.value = null;
    closeModal();
  }
</script>
